package com.example.searchservice.repository;

import com.example.searchservice.doc.UserDocument;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Repository
public interface UserRepository extends ElasticsearchRepository<UserDocument, String> {

    // 自动派生查询
    List<UserDocument> findByName(String name);
    Optional<UserDocument> findByEmail(String email);
    List<UserDocument> findByAgeBetween(int minAge, int maxAge);

    // ES 9.x 新的查询语法
    @Query("""
    {
      "bool": {
        "must": [
          {
            "match": {
              "name": "?0"
            }
          }
        ]
      }
    }
    """)
    List<UserDocument> searchByName(String name);

    // 多字段搜索
    @Query("""
    {
      "multi_match": {
        "query": "?0",
        "fields": ["name", "note", "email"]
      }
    }
    """)
    List<UserDocument> searchAllFields(String query);

    // 聚合查询
    @Query("""
    {
      "aggs": {
        "age_stats": {
          "stats": {
            "field": "age"
          }
        }
      },
      "size": 0
    }
    """)
    Map<String, Object> aggregateAgeStats();

    @Query("{\"match\": {\"name\": \"?0\"}}")
    Page<UserDocument> findByNameContaining(String name, Pageable pageable);

    @Query("{\"bool\": {\"must\": [{\"match\": {\"name\": \"?0\"}}], \"filter\": [{\"range\": {\"age\": {\"gte\": ?1, \"lte\": ?2}}}]}}")
    Page<UserDocument> findByNameContainingAndAgeBetween(String name, Double minAge, Double maxAge, Pageable pageable);
}